package com.lagou.sql.session;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.sql.Executor;
import com.lagou.sql.SimpleExecutor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Kirito
 * @description: SqlSession默认实现
 * @date 2020/03/25
 */
public class DefaultSqlSession implements SqlSession {

    private Executor executor;

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
        this.executor = new SimpleExecutor();
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        // 通过具体的Executor来执行sql并获取返回结果
        MappedStatement statement = configuration.getMappedStatementMap().get(statementId);
        return executor.query(configuration, statement, params);
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("查询数据为空或者返回结果过多");
        }
    }

    @Override
    public void insert(String statementId, Object... params) throws Exception {
        update(statementId, params);
    }

    @Override
    public void update(String statementId, Object... params) throws Exception {
        MappedStatement statement = configuration.getMappedStatementMap().get(statementId);
        executor.update(configuration, statement, params);
    }

    @Override
    public void delete(String statementId, Object... params) throws Exception {
        update(statementId, params);
    }

    @Override
    public <T> T getMapper(Class<?> clazz) {
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {

            /*
             * 调用被代理类的方法时，最终会执行invoke方法
             * Object: 代理对象
             * Method：调用的方法，即需要执行的方法
             * Object[]：方法的参数
             * */
            @Override
            public Object invoke(Object o, Method method, Object[] args) throws Throwable {
                /**
                 * 返回的proxyInstance其实是Dao层接口的代理对象
                 * 目的：通过代理对象调用dao中接口时，去执行JDBC的代码逻辑
                 * 而selectList/selectOne均实现了jdbc的调用逻辑
                 */
                // 调用selectList/selectOne方法需要明确两个参数
                // 1.statementId -> namespace.id组成，考虑用接口的全限定名.方法名来实现statementId
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + methodName;

                // 2.params -> args

                if (methodName.contains("select")) {
                    // 确定调用selectList还是selectOne方法，通过判断method返回值是否包含泛型类型参数如：<T>
                    Type returnType = method.getGenericReturnType();
                    if (returnType instanceof ParameterizedType) {
                        return selectList(statementId, args);
                    }
                    return selectOne(statementId, args);
                } else if (methodName.contains("update")) {
                    update(statementId, args);
                    return o;
                } else if (methodName.contains("delete")) {
                    delete(statementId, args);
                    return o;
                } else if (methodName.contains("insert")) {
                    insert(statementId, args);
                    return o;
                } else {
                    throw new RuntimeException("Not Supported. ");
                }
            }
        });
        return (T) proxyInstance;
    }

    @Override
    public void close() throws SQLException {
        executor.close();
    }
}
